/**
 * 事件处理模块
 */
import { state } from './state.js';
import { updateContentArea, renderSelectedNurses, renderProfessionTabs, renderLevel1, renderLevel2, renderLevel3 } from './ui.js';
import { getNurseList } from './api.js';
import { loadLevel2Data, loadLevel3Data } from './data.js';

/**
 * 检查护士是否已选中
 */
export const isNurseSelected = (nurseId) => {
  return state.selectedNurses.some(item => item.id === nurseId);
};

/**
 * 处理护士点击事件（选中/取消选中）
 */
export const handleNurseClick = (nurse) => {
  console.log('点击护士:', nurse);
  
  const nurseId = nurse.id;
  const currentJob = state.professionList[state.selectedProfessionIndex] || state.professionList[0] || '未知';
  
  // 检查是否已选中
  const selectedIndex = state.selectedNurses.findIndex(item => item.id === nurseId);
  
  if (selectedIndex >= 0) {
    // 如果已选中，则取消选中
    state.selectedNurses.splice(selectedIndex, 1);
    console.log('取消选中护士:', nurse.name);
  } else {
    // 如果未选中，则添加选中
    state.selectedNurses.push({
      id: nurseId,
      name: nurse.name || '未知',
      job: currentJob
    });
    console.log('选中护士:', nurse.name, '职业:', currentJob);
  }
  
  // 更新UI
  updateContentArea();
  renderSelectedNurses();
};

/**
 * 删除选中的护士
 */
export const removeSelectedNurse = (nurseId) => {
  const index = state.selectedNurses.findIndex(item => item.id === nurseId);
  if (index >= 0) {
    state.selectedNurses.splice(index, 1);
    console.log('删除选中护士:', nurseId);
    
    // 更新UI
    updateContentArea();
    renderSelectedNurses();
  }
};

/**
 * 处理职业类型点击事件
 */
export const handleProfessionClick = (index) => {
  // 确保索引有效
  if (index < 0 || index >= state.professionList.length) {
    console.warn('职业类型索引无效:', index);
    return;
  }
  
  state.selectedProfessionIndex = index;
  renderProfessionTabs();
  
  // 如果已选择三级目录项，重新加载护士列表
  if (state.currentLevel3Item) {
    setTimeout(() => {
      getNurseList(state.currentLevel3Item.id);
    }, 300);
  }
};

/**
 * 处理Tab点击事件
 */
export const handleTabClick = async (item, level, index) => {
  console.log(`Tab点击 - 级别${level}:`, item, index);
  
  if (level === 1) {
    state.activeLevel1 = index;
    renderLevel1();
    await loadLevel2Data(index);
  } else if (level === 2) {
    state.activeLevel2 = index;
    renderLevel2();
    await loadLevel3Data(index);
  } else if (level === 3) {
    state.activeLevel3 = index;
    state.currentLevel3Item = item;
    renderLevel3();
    
    // 第三级变化时，加载护士列表
    if (item && item.id) {
      console.log('第三级变化，加载护士列表:', item);
      await getNurseList(item.id);
    } else {
      state.nurseList = [];
      updateContentArea();
    }
  }
};

/**
 * 处理取消按钮点击
 */
export const handleCancel = () => {
  console.log('close');
  
  // 如果是 iframe，发送消息给父窗口
  if (window.parent !== window) {
    window.parent.postMessage({
      type: 'nurse-selector-cancel',
      data: 'close'
    }, '*');
  } else {
    // 非 iframe 环境，触发自定义事件
    const event = new CustomEvent('menuCancel', { detail: 'close' });
    document.dispatchEvent(event);
  }
};

/**
 * 处理确定按钮点击
 */
export const handleConfirm = () => {
  // 获取选中的人物ID列表
  const selectedIds = state.selectedNurses.map(nurse => nurse.id);
  console.log('选中的护士ID列表:', selectedIds);
  
  // 如果是 iframe，发送消息给父窗口
  if (window.parent !== window) {
    window.parent.postMessage({
      type: 'nurse-selector-confirm',
      data: selectedIds
    }, '*');
  } else {
    // 非 iframe 环境，触发自定义事件
    const event = new CustomEvent('menuConfirm', { detail: selectedIds });
    document.dispatchEvent(event);
  }
};

